//
//  TYMBBLeManager.m
//  TY_MotorRemoteControl
//
//  Created by 徐伟新 on 2023/11/16.
//  Copyright © 2023 zhongdaodianzi. All rights reserved.
//

#import "TYMBBLeManager.h"

#define scanMaxSecond 5

@interface TYMBBLeManager () <CBPeripheralDelegate, CBCentralManagerDelegate>
@property (nonatomic, strong) NSTimer *scanTimer;
@property (nonatomic, assign) NSInteger scanNumber;

@end

@implementation TYMBBLeManager

- (NSTimer *)scanTimer {
    if (!_scanTimer) {
        _scanTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            self.scanNumber ++;
            if (self.scanNumber > scanMaxSecond) {
                [self stopScanAction];
            }
        }];
    }
    return _scanTimer;
}

- (NSMutableArray *)peripheralArray {
    if (!_peripheralArray) {
        _peripheralArray = [NSMutableArray array];
    }
    return _peripheralArray;
}

- (void)setIsScaning:(BOOL)isScaning {
    _isScaning = isScaning;
    [Notification_center postNotificationName:BLE_SCAN_STATUS_CHANGE object:nil];
}

//- (CBCentralManager *)centerManager {
//    if (!_centerManager) {
//        _centerManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
//    }
//    return _centerManager;
//}

+ (instancetype)shareInstance {
    static TYMBBLeManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        [manager initAction];

    });
    return manager;
}

#pragma mark - private
- (void)initAction {
    self.centerManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];

    
}

/// 扫描蓝牙
- (void)startScanAction {
    
    if (!self.centerManager.isScanning) {
        [self.scanTimer setFireDate:[NSDate distantFuture]];
        self.scanNumber = 0;
        [self.peripheralArray removeAllObjects];
        [self.centerManager scanForPeripheralsWithServices:nil options:nil];
        [self.scanTimer setFireDate:[NSDate date]];
        self.isScaning = YES;
        
    }
    
}
/// 停止扫描
- (void)stopScanAction {
    
    if (self.centerManager.isScanning) {
        [self.centerManager stopScan];
        [self.scanTimer setFireDate:[NSDate distantFuture]];
        self.scanNumber = 0;
        self.isScaning = NO;
    }
    
}
/// 连接蓝牙
- (void)connectBleWith:(CBPeripheral *)peripheral {
    
    if (peripheral.state != CBPeripheralStateConnected) {
        if (self.peripheral && self.peripheral.state == CBPeripheralStateConnected) {
            [self disConnectedBleWith:self.peripheral];
        }
        [self.centerManager connectPeripheral:peripheral options:nil];
    }else {
        [self disConnectedBleWith:peripheral];
    }
    
}
/// 断开蓝牙连接
- (void)disConnectedBleWith:(CBPeripheral *)peripheral {
    if (peripheral.state == CBPeripheralStateConnected) {
        [self.centerManager cancelPeripheralConnection:peripheral];
    }
}
/// 发送命令
- (void)sendDataWithCommand:(NSString *)command withBlock:(nonnull sendCommandBlock)block {
    NSLog(@"%@ === %@",self.characteristic, self.peripheral);
    if (self.peripheral && self.characteristic) {
        if (self.peripheral.state == CBPeripheralStateConnected) {
            NSLog(@"发送数据：%@",command);
            [self.sendDataArray addObject:command];
            [self.peripheral writeValue:[CalculateTool convertHexStrToMutableData:command] forCharacteristic:self.characteristic   type: CBCharacteristicWriteWithResponse];
            block(YES,@"发送成功");

        }else {
            NSLog(@"蓝牙没连接");
            block(NO,@"请先连接蓝牙");
            [Notification_center postNotificationName:BLE_UNCONNECTED_DEVICE_NOTIFICATION object:nil];
        }
    }else {
        NSLog(@"蓝牙没连接");
        block(NO,@"请先连接蓝牙");
        [Notification_center postNotificationName:BLE_UNCONNECTED_DEVICE_NOTIFICATION object:nil];

    }
    

    
}
/// 自动连接
-(void)autoConnectPeripheral{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *identifier = [userDefaults objectForKey:UD_FOR_LAST_CONNECTED_IDENTIFI];
    NSUUID *uuidID = [[NSUUID alloc]initWithUUIDString:identifier];
    if (identifier.length > 0) {
        NSArray *arrays = [self.centerManager retrievePeripheralsWithIdentifiers:@[uuidID]];
        NSLog(@"%@",arrays);
        for (CBPeripheral *peripheral in arrays) {
            //        if ([identifier isEqualToString:peripheral.identifier.UUIDString]) {
            [self showLoadingHUD:NSLocalizedString(@"connecting",@"正在连接") showView:[UIApplication sharedApplication].keyWindow];
            [self.centerManager connectPeripheral:peripheral options:nil];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self hideHUD:[UIApplication sharedApplication].keyWindow];
            });
            break;
        }
    }
    
}

#pragma mark - CBCenteralManagerDelegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBManagerStateUnknown:{

        }
            break;
        case CBManagerStatePoweredOn:{
            [self startScanAction];
        }
            break;
        case CBManagerStateResetting:{

        }
            break;
        case CBManagerStatePoweredOff:{

        }
            break;
        case CBManagerStateUnsupported:{

        }
            break;
        case CBManagerStateUnauthorized:{

        }
            break;
        default:
            break;
    }
}
#pragma mark - 搜索发现周边蓝牙
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    
    if (![self.peripheralArray containsObject:peripheral] && peripheral.name.length > 0) {
        [self.peripheralArray addObject:peripheral];
        if (self.peripheral != nil && self.peripheral.state == CBPeripheralStateConnected) {
            
        }else{
            if (self.isHandControl == NO) {
                [self autoConnectPeripheral];
            }
        }
        NSLog(@"%@",self.peripheralArray);
        [NSObject postNoticationWithName:BLE_SCAN_UPDATE_NOTIFICATION withObject:nil];
    }
}

#pragma mark - 蓝牙连接回调
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"%@蓝牙连接成功",peripheral.name);
    self.isHandControl = NO;
    self.peripheral = peripheral;
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
    if ([self.peripheralArray containsObject:peripheral]) {
        [self.peripheralArray removeObject:peripheral];
    }
    [self stopScanAction];
    [self hideHUD:[UIApplication sharedApplication].keyWindow];
    [NSObject postNoticationWithName:BLE_CONNECTED_SUCCESS_NOTIFICATION withObject:nil];
    
    
}
#pragma mark - 蓝牙断开回调
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"%@蓝牙断开",peripheral.name);
    
    if (self.isHandControl == NO) {
        [self autoConnectPeripheral];
    }
    [self startScanAction];
    [NSObject postNoticationWithName:BLE_DISCONNECTED_FAIL_NOTIFICATION withObject:nil];
    
}
#pragma mark - 发现服务

#pragma mark - 发现服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *service in peripheral.services) {
        NSLog(@"服务:%@\n",service);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}





#pragma mark - 发现服务特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for (CBCharacteristic *cha in service.characteristics) {
        NSLog(@"%s, didDiscoverCharacteristicsForService = %d, char = %@", __FUNCTION__, __LINE__, cha);
        
        if ([cha.UUID.UUIDString isEqualToString:@"FFF1"]) {
            self.characteristic = cha;
            [peripheral setNotifyValue:YES forCharacteristic:cha];
            [Notification_center postNotificationName:BLE_CHARACTERISTIC_OPEN_NOTI object:nil];
            
        }
    }
    
}


#pragma mark - 读取特征返回信息
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSData * data = characteristic.value;
    NSString *dataString = [CalculateTool convertDataToHexStr:data];
    [self.receiveDataArray addObject:dataString];
    [Notification_center postNotificationName:BLE_RECEIVE_DATA_NOTIFICATION object:dataString];
    
    
    
    
    
}

- (NSMutableArray *)sendDataArray {
    if (!_sendDataArray) {
        _sendDataArray = [NSMutableArray array];
    }
    return _sendDataArray;
}

- (NSMutableArray *)receiveDataArray {
    if (!_receiveDataArray) {
        _receiveDataArray = [NSMutableArray array];
    }
    return _receiveDataArray;
}

@end
